package com.jt;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.atomic.AtomicLong;

//扫描启动类所在包或子包中的类，假如接口上有注解描述。则对这样的接口创建其实现类，在实现类内部帮我们进行远程服务调用
@EnableFeignClients
@SpringBootApplication
public class CousumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(CousumerApplication.class,args);
    }
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @LoadBalanced
    @Bean
    public RestTemplate loadBalanceRestTemplate(){
        return new RestTemplate();
    }

    @Service
    public class ConsumerService{
        @SentinelResource("doGetResource")
        public String doGetResource(){
            return "doGetResource";
        }
    }
    @RestController
    public class ConsumerController{
        @Autowired
        private RestTemplate restTemplate;
        @Autowired
        private LoadBalancerClient loadBalancerClient;

        private AtomicLong atomicLong = new AtomicLong(1);

/*
@Autowired注解描述属性时，会告诉spring框架，要优先按属性类型进行对象的查找和注入
假如此类型的对象存在多个，测试还会按照属性名进行查找和比对，有相同的则直接注入（DI），
没有相同的则出错，当然也可以在属性上添加@Qualifier("bean的名字")注解，指定要注入的具体对象
 */
        @Autowired
        private ConsumerService consumerService;
        @Autowired
        private RestTemplate loadBalanceRestTemplate;
        @Value("${server.port:8080}")
        private String server;
        @GetMapping("/consumen/findById")
        @SentinelResource("res")//sentinel资源名
        //@RequestParam(required = false)  可以传值也可以不传值
        //@RequestParam(required = true)    必须传值
        //单机阈值  每秒点击次数
        public String doFindById(@RequestParam(required = false) Integer id){
            return "id = "+id;
        }
        @GetMapping("/consumer/echo/{msg}")
        public String doRestEcho(@PathVariable String msg) throws InterruptedException {
            long num  = atomicLong.getAndIncrement();
            if(num%2==0){
                Thread.sleep(200);
            }
//            String url1 = "http://localhost:8081/provider/echo/"+msg;
//            String url2 = "http://localhost:8080/provider/echo/"+msg;
//            String[] urls ={url1,url2};
//            int n = new Random().nextInt(urls.length);
//            System.out.println(n);
//            return restTemplate.getForObject(urls[n],String.class);
            //return server+"sf"+msg;

            //基于loadBalancerClient方式获取服务实例
            String serviceID="sca-provider";
            ServiceInstance choose = loadBalancerClient.choose(serviceID);
            String ip = choose.getHost();
            int port = choose.getPort();
            //String url = "http://"+ip+":"+port+"/provider/echo/"+msg;
            consumerService.doGetResource();
            String url = String.format("http://%s:%s//provider/echo/%s",ip,port,msg);
            return restTemplate.getForObject(url,String.class);
        }
        //http://localhost:8095/consumer2/echo/
        @GetMapping("/consumer2/echo/{msg}")
        public String doRestEcho2(@PathVariable String msg){
            consumerService.doGetResource();
            String serviceID = "sca-provider";
            String url = String.format("http://%s/provider/echo/%s",serviceID,msg);
            return loadBalanceRestTemplate.getForObject(url,String.class);
        }
    }
}
